﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Timers;

namespace blackhouse.WebNemo.Data.Cache {
    public class NemoChangeMonitor : ChangeMonitor {

        #region Fields

        private NemoCache cache = new NemoCache(TimeSpan.FromMinutes(2), ConfigurationManager.AppSettings["MSSQLConnectionString"]);
        private ReadOnlyCollection<string> keys;
        private Timer timer;
        private DateTime lastTime;

        #endregion

        #region Properties

        public override string UniqueId {
            get { return this.cache.GetCurrentCacheKey(); }
        }

        #endregion

        #region Constructors

        public NemoChangeMonitor(params int[] groupIds) {
            this.cache.Reset();
            this.cache.SetKey("monitor");
            this.cache.SetDependencyTables(groupIds);
            this.keys = new List<string>(groupIds.Select(s => s.ToString())).AsReadOnly();
            this.lastTime = this.cache.GetLastUpdateTime();
            this.timer = new Timer();
            this.timer.Interval = 1000;
            this.timer.Elapsed += CheckIsChanged;
            this.timer.Enabled = true;
            this.InitializationComplete();
        }


        #endregion

        private void CheckIsChanged(object sender, ElapsedEventArgs e) {
            if (this.cache.GetLastUpdateTime() > this.lastTime)
                OnChanged(null);
        }

        protected override void Dispose(bool disposing) {
            this.timer.Dispose();
            this.cache = null;
        }

    }
}
